import Vue from "vue";
import Vuex from "vuex";
import mapData from "./mapdata";

Vue.use(Vuex);

const initSysDate = (from, to) => {
  const srcDate = from || new Date();
  const destDate = to || {
    year: 0,
    month: 0,
    day: 0,
    date: null
  };

  destDate.year = srcDate.getFullYear();
  destDate.month = srcDate.getMonth() + 1;
  destDate.day = srcDate.getDate();
  destDate.date = srcDate;

  return destDate;
}

export default new Vuex.Store({
  state: {
    theme: "linght",
    schema: process.env.VUE_APP_SCHEMA,
    schema_di: process.env.VUE_APP_SCHEMA_DI,
    remUnit: 16, // 页面根字体大小
    visitRoute: [], // 下钻路由

    sysDate: initSysDate(),
  },
  getters: {
    // 根据log获取缓存数据
    getCashData: (state) => (path) => {
      if (path) {
        let pList = path.split('-');
        let pObj = state.cashData;
        try {
          // 依次获取至路径数据
          for (let i = 0, len = pList.length; i < len; i++) {
            pObj = pObj[`$${pList[i]}`]
          }
          return pObj.data
        } catch (e) {
          // 若不存在此路径的数据 返回空
          return []
        }
      }
      return []
    }
  },
  mutations: {
    setCashData(state, payload) {
      state.cashData = payload
    },
    setSysDate(state, date) {
      initSysDate(date, state.sysDate);
    },
    setRemUnit(state, size) {
      state.remUnit = size;
      document.documentElement.style.fontSize = `${size}px`
    },
    addRoute(state, route) {
      state.visitRoute.push(route)
    },
    backRoute(state) {
      state.visitRoute.pop()
    },
    clearRoute(state) {
      state.visitRoute = []
    },
  },
  actions: {
    addRoute(context, route) {
      context.commit("addRoute", route);
    },
    backRoute(context) {
      context.commit("backRoute");
    },
    clearRoute(context) {
      context.commit("clearRoute");
    },
  },
  modules: {
    mapData,
  },
});